// Copyright (c) 2007 Robin Boerdijk. All rights reserved.
//
// This software is licensed under the terms of the Microsoft Reciprocal License as described 
// in the file LICENSE.txt, which you should have received as part of this distribution. The 
// license terms are also available at http://www.opensource.org/licenses/ms-rl.html.

#include "wtkpc.h"

#include "wtk/Error.h"

#include <windows.h>

#include <string>
#include <iostream>

namespace wtk
{
	std::runtime_error Error(const std::string &problem, DWORD errorCode)
	{
		DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
		LPCVOID source = NULL;
		DWORD messageId = errorCode;
		DWORD languageId = 0;
		char buffer[4096];
		DWORD size = sizeof(buffer);
		va_list *arguments = NULL;

		DWORD result = FormatMessageA(flags, source, messageId, languageId, buffer, size, arguments);
		if (result == 0) {
			std::cerr << "Panic: FormatMessage() failed in " __FUNCTION__ " with error code " << GetLastError() << std::endl;
			abort();
		}
		return std::runtime_error(problem + ": " + std::string(buffer, result));
	}

	std::runtime_error Error(const std::string &problem)
	{
		return Error(problem, GetLastError());
	}
}